import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
mnist=tf.keras.datasets.mnist
(x_train,y_train),(x_test,y_test)=mnist.load_data()
x_train,x_test=x_train/255.0,x_test/255.0
model=tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128,activation='relu'))
model.add(tf.keras.layers.Dense(10,activation='softmax'))
model.summary()
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['sparse_categorical_accuracy'])
model.fit(x_train,y_train,batch_size=32,epochs=5)
model.evaluate(x_test,y_test,batch_size=32,verbose=2)
for i in range(5):
    t=np.random.randint(1,10000)
    x=tf.reshape(x_test[t],(1,28,28))
    y_pred=np.argmax(model.predict(x),axis=1)
    plt.subplot(1,5,i+1)
    plt.rcParams['font.sans-serif']=['SimHei']
    plt.axis("off")
    plt.imshow(x_test[t],cmap='gray')
    title="标签值:"+str(y_test[t])+"\n预测值:"+str(y_pred[0])
    plt.title(title)
plt.show()